#!/usr/bin/env node
"use strict";

/**
 * Remove normal spaces and newline characters (\r, \n) from the given text.
 * Tabs and other whitespace characters are preserved.
 * @param {string} text
 * @returns {string}
 */
function removeSpacesAndNewlines(text) {
  if (typeof text !== "string") {
    return "";
  }
  return text.replace(/[ \r\n]+/g, "");
}

function showUsageAndExit() {
  const message = [
    "Usage:",
    "  node remove-whitespace.js \"your text here\"",
    "  echo \"your text here\" | node remove-whitespace.js",
    "",
    "Description:",
    "  Removes spaces and newline characters (\\r, \\n) from input text.",
  ].join("\n");
  console.error(message);
  process.exit(1);
}

async function main() {
  const hasArg = process.argv.length > 2;

  if (hasArg) {
    const input = process.argv.slice(2).join(" ");
    const output = removeSpacesAndNewlines(input);
    process.stdout.write(output);
    return;
  }

  if (process.stdin.isTTY) {
    showUsageAndExit();
    return;
  }

  let data = "";
  process.stdin.setEncoding("utf8");
  process.stdin.on("data", (chunk) => {
    data += chunk;
  });
  process.stdin.on("end", () => {
    const output = removeSpacesAndNewlines(data);
    process.stdout.write(output);
  });
}

if (require.main === module) {
  main();
}

module.exports = removeSpacesAndNewlines;


